package 临时工具.粮仓.APDU;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class APDUUtil {

    public static final byte[] SYNC_BYTES = {(byte) 0xEB, (byte) 0x90, (byte) 0xEB, (byte) 0x90};

    public static byte[] buildAPDU(short msgId, byte[] asduData) {
        ByteBuffer buffer = ByteBuffer.allocate(16 + asduData.length);
        buffer.order(ByteOrder.LITTLE_ENDIAN);

        // 同步符
        buffer.put(SYNC_BYTES);

        // 长度（ASDU部分长度）
        buffer.putShort((short) asduData.length);

        // 报文ID
        buffer.putShort(msgId);

        // 预留字段
        buffer.put(new byte[8]);

        // ASDU 数据
        buffer.put(asduData);

        return buffer.array();
    }

    public static void parseAPDU(byte[] apdu) {
        ByteBuffer buffer = ByteBuffer.wrap(apdu);
        buffer.order(ByteOrder.LITTLE_ENDIAN);

        byte[] sync = new byte[4];
        buffer.get(sync);

        short length = buffer.getShort();
        short msgId = buffer.getShort();

        byte[] reserved = new byte[8];
        buffer.get(reserved);

        byte[] asdu = new byte[length];
        buffer.get(asdu);

        System.out.println("同步符: " + bytesToHex(sync));
        System.out.println("长度: " + length);
        System.out.println("报文ID: " + msgId);
        System.out.println("ASDU内容: " + new String(asdu));
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes)
            sb.append(String.format("%02X ", b));
        return sb.toString();
    }
}
